import axios from 'axios'
import qs from 'qs'
import lc from './../unit/lc'
import { MessageBox } from 'mint-ui';
import {Toast,Indicator} from 'mint-ui';


axios.defaults.timeout = 60000;

axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';

axios.interceptors.request.use(function (config){
  // 在发送请求之前做些什么
  //TODO:稍后将api中的信息传过来替换text中的文字，实现请求的字符替换，这部分代码需要做
  Indicator.open({
    text: '加载中...',
    spinnerType: 'fading-circle'
  });
  if (config.method.toLowerCase() == 'post'){
    config.data = qs.stringify(config.data)
  }
  return config;
}, function (error) {
  // 对请求错误做些什么
  Toast({
    message: '错误的传参',
    position: 'bottom',
    duration: 3000
  });
  return Promise.reject(error);
});

// 添加响应拦截器
axios.interceptors.response.use(function (response) {
  // 对响应数据做点什么
  Indicator.close();
  //TODO:正式环境解封
  if(response.data.code == lc.repeatCode){
    MessageBox.alert('您的token已过期，请退出重新登陆', '警告');
  }
  else if(response.data.code != 1){
    //TODO:测试环境用，这部分代码需要做
    Toast(response.data.msg);
    return Promise.reject(response);
  }
  return response;
}, function (error) {
  // 对响应错误做点什么
  Indicator.close();
  Toast({
    message: '网络异常或网络请求超时，请稍后重试',
    position: 'bottom',
    duration: 3000
  });
  return Promise.reject(error);
});

function axiosFactory(method,url, params,sign1){
  if(method.toLowerCase() == 'get'){
    return axios({
      method: method,
      url: url,
      params: params,
      headers:{
        sign:sign1
      }
    })
  }else{
    return axios({
      method: method,
      url: url,
      data: params,
      headers:{
        sign:sign1
      }
    })
  }
}
function axiosFactory1(method,url, params) {
  if(method.toLowerCase() == 'get'){
    return axios({
      method: method,
      url: url,
      params: params
    })
  }else{
    return axios({
      method: method,
      url: url,
      data: params
    })
  }
}

const s = '654321';

export default function fetch(method,url, params,text){
  if(params.sysVer){
    let _obj = lc.ziDianXu(params);
    let mdSign = md5(s+_obj).toUpperCase();
    return new Promise((resolve, reject) => {
      axiosFactory(method,url, params,mdSign)
        .then(response => {
          resolve(response.data);
        }, err => {
          reject(err);
        })
        .catch((error) => {
          reject(error)
        })
    })
  }else{
    return new Promise((resolve, reject) => {
      axiosFactory1(method,url, params)
        .then(response => {
          resolve(response.data);
        }, err => {
          reject(err);
        })
        .catch((error) => {
          reject(error)
        })

    })
  }
};



















